//
//  ShoppingCartViewController.m
//  cm
//
//  Created by suyibaishan on 2017/10/25.
//  Copyright © 2017年 feihu. All rights reserved.
//

#import "ShoppingCartViewController.h"
#import "ShoppingCartCell.h"
//#import "SubmitViewController.h"
#import "IndentViewController.h"
//#import "GoodsDetailViewController.h"
#import "LoginViewController.h"
#import "IndentViewController.h"

#define tabBarHeight  self.tabBarController.tabBar.frame.size.height

@interface ShoppingCartViewController () <UITableViewDelegate,UITableViewDataSource,ShoppingCartCellDelegate,UITextViewDelegate>
{
    UITableView *_tableView;
    MBProgressHUD *HUD;
    float allPrice;
    NSInteger allNumber;
    NSMutableArray *dataSource;
    NSMutableArray *infoArr;
    NSMutableArray *itemArr;
    UIView *headView;
    UIView *footView;
    UIView *settleView;
    UILabel *settleLabel;
    UILabel *settleLab;
    UIImageView *cartImg;
    UILabel *cartLabel;
//    UIButton *cartBtn;
    NSInteger selectNum;
    UITextView *remarkView;
    UILabel *placeholderLab;
    UIButton *submitBtn;
    BOOL moveUp;
}
@end

@implementation ShoppingCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createShoppingCartView];
    
    [self reloadData];
}

-(void)reloadData
{
    [[ToolNet sharedManager] getUserInfo:[mUserDefaults objectForKey:@"userCode"] accessToken:[mUserDefaults objectForKey:@"accessToken"] url:MMyItem completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            [dataSource removeAllObjects];
            [infoArr removeAllObjects];
            [dataSource addObjectsFromArray:responseJson[@"data"]];
            [_tableView reloadData];
            if (dataSource.count == 0) {
                settleView.hidden = YES;
                cartImg.hidden = NO;
                cartLabel.hidden = NO;
            }
            else
            {
                settleView.hidden = NO;
                cartImg.hidden = YES;
                cartLabel.hidden = YES;
            }
            
            [itemArr removeAllObjects];
            for (NSInteger i = 0; i < dataSource.count; i++) {
                [itemArr addObject:@{}];
            }
//            _allSelectBtn.tag = 1;
//            [self selectShopingCart:_allSelectBtn];
        }
//        else {
//            [self showMessage:responseJson[@"msg"]];
//        }
    }];
}

-(void)createShoppingCartView
{
    self.titleLabel.text = @"购物车";
//    UIImage *deleteImg = [[UIImage imageNamed:@"delete"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:deleteImg style:UIBarButtonItemStylePlain target:self action:@selector(deleteHandler)];
    //    [self createHeadView];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.baseBarHeight, kScreenWidth, kScreenHeight - self.baseBarHeight - tabBarHeight) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    //    [self createFootView];
    //    _tableView.tableFooterView = footView;
    
    [self createSettleView];
    
    cartImg = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth-240)/2, kScreenWidth*0.4f, 60, 60)];
    cartImg.image = [UIImage imageNamed:@"cm_cart"];
    cartImg.hidden = YES;
    [self.view addSubview:cartImg];
//    cartImg.backgroundColor = [UIColor redColor];
    
    cartLabel = [[UILabel alloc] init];
    cartLabel.textAlignment = NSTextAlignmentCenter;
    cartLabel.font = [UIFont systemFontOfSize:19];
    cartLabel.text = @"您的购物车暂无商品";
    cartLabel.textColor = [UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1];
    cartLabel.hidden = YES;
    [self.view addSubview:cartLabel];
    cartLabel.sd_layout
    .topSpaceToView(self.view, kScreenWidth*0.45f)
    .leftSpaceToView(cartImg, 5)
    .widthIs(190)
    .heightIs(30);
    
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    
    dataSource = [NSMutableArray array];
    infoArr = [NSMutableArray array];
    itemArr = [NSMutableArray array];
//    cartItemArr = [NSMutableArray array];
}

-(void)showSubmitView
{
//    SubmitViewController *submitVC = [[SubmitViewController alloc] init];
//    [self.navigationController pushViewController:submitVC animated:NO];
}

//-(void)deleteHandler
//{
//    if (selectNum == 0) {
//        [self showMessage:@"您还没有勾选任何商品!"];
//    }
//    else
//    {
//        
//    }
//}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //    _allSelectBtn.tag = 1;
    //    [self selectBtnClick:_allSelectBtn];
    [self reloadData];
}

-(void)cartBtnHandler
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CATEGORYVIEW" object:nil];
}

-(UIView *)createSettleView
{
    settleView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - tabBarHeight - 45, kScreenWidth, 45)];
    settleView.backgroundColor = [UIColor whiteColor];
    settleView.hidden = YES;
    [self.view addSubview:settleView];
    
    _allSelectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _allSelectBtn.frame = CGRectMake(10, 10, 25, 25);
    [_allSelectBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
    [_allSelectBtn setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateSelected];
    [_allSelectBtn addTarget:self action:@selector(selectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [settleView addSubview:_allSelectBtn];
    
    UILabel *chooseLab = [[UILabel alloc] init];
    chooseLab.text = @"全选";
    chooseLab.font = [UIFont systemFontOfSize:13];
    chooseLab.textColor = [UIColor colorWithRed:0.33 green:0.33 blue:0.33 alpha:1];
    [settleView addSubview:chooseLab];
    chooseLab.sd_layout
    .topSpaceToView(settleView, 10)
    .leftSpaceToView(_allSelectBtn, 5)
    .widthIs(50)
    .heightIs(25);
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1];
    [settleView addSubview:line];
    line.sd_layout
    .topSpaceToView(settleView, 0)
    .leftSpaceToView(settleView, 0)
    .widthIs(kScreenWidth)
    .heightIs(0.5);
    
    submitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    submitBtn.frame = CGRectMake(kScreenWidth - 105, 0, 105, 45);
    [submitBtn setTitle:@"提交订单" forState:UIControlStateNormal];
    [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    submitBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    submitBtn.backgroundColor = [UIColor colorWithRed:0.19 green:0.53 blue:0.98 alpha:1];
    [submitBtn addTarget:self action:@selector(submitBtnHanlder) forControlEvents:UIControlEventTouchUpInside];
    [settleView addSubview:submitBtn];
    
    settleLabel = [[UILabel alloc] init];
    settleLabel.font = [UIFont systemFontOfSize:12];
    settleLabel.textAlignment = NSTextAlignmentRight;
    settleLabel.textColor = [UIColor colorWithRed:0.95 green:0 blue:0 alpha:1];
    [settleView addSubview:settleLabel];
    settleLabel.sd_layout
    .topSpaceToView(settleView, 10)
    .rightSpaceToView(submitBtn, 10)
    .widthIs(kScreenWidth - 150)
    .heightIs(25);
    
    return settleView;
}

-(void)submitBtnHanlder
{
    if (selectNum == 0) {
        [self showMessage:@"您还没有勾选任何商品!"];
    }
    else
    {
        [itemArr removeObject:@{}];
//        NSLog(@"itemArr~~~~~~~~~~~~~~~~~%@",itemArr);
        allPrice = 0.0;
        allNumber = 0;
        selectNum = 0;
        _allSelectBtn.selected = NO;
        _allSelectBtn.tag = 0;
        IndentViewController *indentVC = [[IndentViewController alloc] init];
        indentVC.dataSource = itemArr;
        [self.navigationController pushViewController:indentVC animated:YES];
    }
}

//-(void)selectShopingCart:(UIButton *)sender
//{
//    sender.selected = YES;
//
//    selectNum = dataSource.count;
//    //    NSLog(@"selectNum:%ld",selectNum);
//    //改变单元格选中状态
//    for (NSInteger i = 0; i < dataSource.count; i++)
//    {
//        [infoArr addObject:[[ShoppingModel alloc] initWithDictionary:dataSource[i]]];
//        ShoppingModel *model = infoArr[i];
//        model.selectState = sender.tag;
//    }
//    [itemArr removeAllObjects];
//    [cartItemArr removeAllObjects];
//    for (NSDictionary *dict in dataSource) {
//        [itemArr addObject:dict[@"productNo"]];
//        [cartItemArr addObject:dict[@"cartItemId"]];
//    }
//    //计算价格
//    [self totalPrice];
//    //刷新表格
//    [_tableView reloadData];
//}

#pragma - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier =  @"indentifier";
    ShoppingCartCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell = [[ShoppingCartCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.delegate = self;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    ShoppingModel *model = [[ShoppingModel alloc] initWithDictionary:dataSource[indexPath.row]];
    //将数据模型放入数组中
    [infoArr addObject:model];
    
    cell.model = infoArr[indexPath.row];
    
    [cell setSelectAction:^{
        /**
         *  判断当期是否为选中状态，如果选中状态点击则更改成未选中，如果未选中点击则更改成选中状态
         */
        ShoppingModel *model = infoArr[indexPath.row];
        
        if (model.selectState == YES)
        {
            model.selectState = NO;
            selectNum--;
            [itemArr replaceObjectAtIndex:indexPath.row withObject:@{}];
        }
        else
        {
            model.selectState = YES;
            selectNum++;
            [itemArr replaceObjectAtIndex:indexPath.row withObject:dataSource[indexPath.row]];
        }
        //刷新当前行
        [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        if (selectNum == dataSource.count) {
            _allSelectBtn.selected = YES;
            _allSelectBtn.tag = 1;
        }
        else
        {
            _allSelectBtn.selected = NO;
            _allSelectBtn.tag = 0;
        }
        
        [self totalPrice];
    }];
    
    [cell setTapAction:^{
//        GoodsDetailViewController *goodsDetailVC = [[GoodsDetailViewController alloc] init];
//        goodsDetailVC.goodsId = [dataSource[indexPath.row][@"goodsId"] integerValue];
//        [self.navigationController pushViewController:goodsDetailVC animated:YES];
    }];
    
    [cell setDeleteAction:^{
        [[ToolNet sharedManager] delItem:[mUserDefaults objectForKey:@"userCode"] accessToken:[mUserDefaults objectForKey:@"accessToken"] itemId:model.itemId url:MDelItem completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
            if ([responseJson[@"code"] isEqual:@1]) {
                [self reloadData];
            }
            else {
                [self showMessage:responseJson[@"msg"]];
            }
        }];
    }];
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 95;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    //    /**
    //     *  判断当期是否为选中状态，如果选中状态点击则更改成未选中，如果未选中点击则更改成选中状态
    //     */
    //    ShoppingModel *model = infoArr[indexPath.row];
    //
    //    if (model.selectState == YES)
    //    {
    //        model.selectState = NO;
    //        selectNum--;
    //        [itemArr removeObject:dataSource[indexPath.row][@"productNo"]];
    //    }
    //    else
    //    {
    //        model.selectState = YES;
    //        selectNum++;
    //        [itemArr addObject:dataSource[indexPath.row][@"productNo"]];
    //    }
    //
    //    //刷新当前行
    //    [_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    //
    //    if (selectNum == dataSource.count) {
    //        _allSelectBtn.selected = YES;
    //        for (NSDictionary *dict in dataSource) {
    //            [itemArr addObject:dict[@"productNo"]];
    //        }
    //    }
    //    else
    //    {
    //        _allSelectBtn.selected = NO;
    //        [itemArr removeAllObjects];
    //    }
    //
    //    [self totalPrice];
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //删除indexPath指定的单元格
        [HUD show:YES];
        [[ToolNet sharedManager] delItem:[mUserDefaults objectForKey:@"userCode"] accessToken:[mUserDefaults objectForKey:@"accessToken"] itemId:[dataSource[indexPath.row][@"id"] integerValue] url:MDelItem completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
            if ([responseJson[@"code"] isEqual:@1]) {
                [HUD hide:YES];
                [self reloadData];
            }
            else {
                [self showMessage:responseJson[@"msg"]];
            }
        }];
    }
}

/**
 *  全选按钮事件
 *
 *  @param sender 全选按钮
 */
-(void)selectBtnClick:(UIButton *)sender
{
    //判断是否选中，是改成否，否改成是，改变图片状态
    sender.tag = !sender.tag;
    if (sender.tag) {
        sender.selected = YES;
        selectNum = dataSource.count;
    }
    else
    {
        sender.selected = NO;
        selectNum = 0;
    }
    //改变单元格选中状态
    for (NSInteger i = 0; i < dataSource.count; i++)
    {
        ShoppingModel *model = infoArr[i];
        model.selectState = sender.tag;
        NSLog(@"sender.tag:%ld",(long)sender.tag);
    }
    [itemArr removeAllObjects];
    for (NSDictionary *dict in dataSource) {
        [itemArr addObject:dict];
    }
    //计算价格
    [self totalPrice];
    //刷新表格
    [_tableView reloadData];
}

#pragma mark -- 实现加减按钮点击代理事件
/**
 *  实现加减按钮点击代理事件
 *
 *  @param cell 当前单元格
 *  @param flag 按钮标识，11 为减按钮，12为加按钮
 */
-(void)btnClick:(UITableViewCell *)cell andFlag:(NSInteger)flag
{
    NSIndexPath *index = [_tableView indexPathForCell:cell];
    ShoppingModel *model = infoArr[index.row];
    switch (flag) {
        case 1000:
        {
            //做减法
            //先获取到当期行数据源内容，改变数据源内容，刷新表格
            if (model.goodsNum > 1)
            {
                model.goodsNum --;
            }
            [[ToolNet sharedManager] changeItem:[mUserDefaults objectForKey:@"userCode"] accessToken:[mUserDefaults objectForKey:@"accessToken"] itemId:model.itemId quantity:model.goodsNum url:MChangeItem completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
                if ([responseJson[@"code"] isEqual:@1]) {
                    //刷新表格
                    [_tableView reloadData];
                    //计算总价
                    [self totalPrice];
                    [[ToolNet sharedManager] getUserInfo:[mUserDefaults objectForKey:@"userCode"] accessToken:[mUserDefaults objectForKey:@"accessToken"] url:MMyItem completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
                        if ([responseJson[@"code"] isEqual:@1]) {
                            [itemArr replaceObjectAtIndex:index.row withObject:responseJson[@"data"][index.row]];
                        }
                    }];
                }
                else {
                    [self showMessage:responseJson[@"msg"]];
                }
            }];
        }
            break;
        case 1001:
        {
            model.goodsNum ++;
            [[ToolNet sharedManager] changeItem:[mUserDefaults objectForKey:@"userCode"] accessToken:[mUserDefaults objectForKey:@"accessToken"] itemId:model.itemId quantity:model.goodsNum url:MChangeItem completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
                if ([responseJson[@"code"] isEqual:@1]) {
                    //刷新表格
                    [_tableView reloadData];
                    //计算总价
                    [self totalPrice];
                    [[ToolNet sharedManager] getUserInfo:[mUserDefaults objectForKey:@"userCode"] accessToken:[mUserDefaults objectForKey:@"accessToken"] url:MMyItem completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
                        if ([responseJson[@"code"] isEqual:@1]) {
                            [itemArr replaceObjectAtIndex:index.row withObject:responseJson[@"data"][index.row]];
                        }
                    }];
                }
                else {
                    [self showMessage:responseJson[@"msg"]];
                }
            }];
        }
            break;
        default:
            break;
    }
}

#pragma mark -- 计算价格
-(void)totalPrice
{
    //遍历整个数据源，然后判断如果是选中的商品，就计算价格（单价 * 商品数量）
    for ( NSInteger i = 0; i<infoArr.count; i++)
    {
        ShoppingModel *model = infoArr[i];
        if (model.selectState)
        {
            allPrice = allPrice + model.goodsNum * model.downPayment;
            allNumber = allNumber + model.goodsNum;
        }
    }
    
    //给总价文本赋值
    settleLabel.text = [NSString stringWithFormat:@"共%ld件，合计：¥%.2f",allNumber,allPrice];
    NSLog(@"%f",allPrice);
    
    //每次算完要重置为0，因为每次的都是全部循环算一遍
    allPrice = 0.0;
    allNumber = 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
